package freespiritsocial.io.user.network

import android.text.TextUtils
import android.util.Log
import com.alibaba.fastjson.JSONObject
import freespiritsocial.io.user.BuildConfig
import freespiritsocial.io.user.util.CacheUtil
import me.hgj.jetpackmvvm.ext.util.loge
import me.hgj.jetpackmvvm.util.Base64
import me.hgj.jetpackmvvm.util.LogUtils
import me.hgj.jetpackmvvm.util.MD5Utils
import me.hgj.jetpackmvvm.util.RandomString
import okhttp3.Interceptor
import okhttp3.Request
import okhttp3.Response
import okio.Buffer
import java.nio.charset.Charset
import java.util.*

/**
 * 自定义头部参数拦截器，传入heads
 */
class MyHeadInterceptor: Interceptor {

    companion object {
        @Volatile
        var isFile: Boolean = false

        const val HTTP_FILE = "HTTP_FILE"
    }

    @Throws(Exception::class)
    override fun intercept(chain: Interceptor.Chain): Response? {
        val builder = chain.request().newBuilder()
        builder.addHeader("token",CacheUtil.token).build()
        val jsonObject = JSONObject().apply {
            put("appType","0")
            put("platformType","1")
            put("versionCode",BuildConfig.VERSION_NAME)
            put("uuid",CacheUtil.getUUID())
            LogUtils.e(CacheUtil.getUUID())
        }
        builder.addHeader("VersionInfo",Base64.encode(jsonObject.toString().toByteArray()))
        val nonceStr = RandomString(16).nextString()//随机字符串
        val utcStr = System.currentTimeMillis().toString()//时间戳
        builder.addHeader("nonceStr",nonceStr)
            .addHeader("utcStr",utcStr)
            .addHeader("Accept-Language","en-US")
            .removeHeader("User-Agent")
        var request = builder.build()
        var isFile = false
        val tag: Any? = request.tag(String::class.java)
        if (tag != null) {
            isFile = tag.toString() == HTTP_FILE
        }
        request = if (isFile) {
            setFileHead(nonceStr,utcStr,builder,request)
        } else {
            try {
                setNormalHead(request,nonceStr,utcStr,builder)
            } catch (e: NumberFormatException) {
                setFileHead(nonceStr,utcStr,builder,request)
            }
        }
        return try {
            chain.proceed(request)
        } catch (e: java.lang.Exception) {
            val url = request.url()
            "----------------- $url -----------------".loge("Exception")
            chain.proceed(request)
        }
    }

    @Throws(NumberFormatException::class)
    private fun setNormalHead(
        request: Request,
        nonceStr: String?,
        utcStr: String,
        builder: Request.Builder
    ): Request {
        var request1 = request
        val queryKeyNames = request1.url().queryParameterNames()
        //进行排序
        val paramMap = TreeMap<String,String?>()
        val requestBody = request1.body()
        if (requestBody != null) {
            val bufferedSink = Buffer()
            request1.body()!!.writeTo(bufferedSink)
            val content = bufferedSink.readString(Charset.forName("UTF-8"))
            Log.e("Tag","intercept:  $content")
            try {
                val requestJsonObject = JSONObject.parseObject(content)
                if (requestJsonObject != null) {
                    for (entry in requestJsonObject.entries) {
                        if (entry.value != null) {
                            paramMap[entry.key] = entry.value.toString()
                        }
                    }
                }
            } catch (e: java.lang.Exception) {
            }
        }
        paramMap["nonceStr"] = nonceStr//随机字符串
        paramMap["utcStr"] = utcStr//时间戳
        for (s in queryKeyNames) {
            paramMap[s] = request1.url().queryParameter(s)
        }
        val iterator = paramMap.entries.iterator()
        val buffer = StringBuffer()
        while (iterator.hasNext()) {
            val entry = iterator.next() as Map.Entry<*,*>
            val key = entry.key as String
            val value = entry.value as String
            if (!TextUtils.isEmpty(value)) {
                Log.e("tag","$key=$value")
                buffer.append("$key=$value")
                buffer.append("&")
            }
        }
        buffer.append("key=peachtechnehkcnskklwe33dsasdferek")//这是和后端约定好的key
        builder.addHeader("Sign",MD5Utils.md5(buffer.toString()).toUpperCase())
            .addHeader("Content-Type","application/json;charset=utf-8")
            .addHeader("user-agent","Android")
        request1 = builder.build()
        return request1
    }

    private fun setFileHead(
        nonceStr: String?,
        utcStr: String,
        builder: Request.Builder,
        request: Request
    ): Request {
        var request1 = request
        val buffer = StringBuffer()
        buffer.append("nonceStr=").append(nonceStr).append("&")//随机字符串
            .append("utcStr=").append(utcStr).append("&")//时间戳
            .append("key=peachtechnehkcnskklwe33dsasdferek")//这是和后端约定好的key
        builder.addHeader("Sign",MD5Utils.md5(buffer.toString()).toUpperCase())
            .addHeader("Content-Type","application/json;charset=utf-8")
            .addHeader("user-agent","Android")
        request1 = builder.build()
        isFile = false
        return request1
    }


}